package com.lagou.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class NettyClient {

    private static final int MAX_RETRY = 2;
    private static Channel channel;
    private static ChannelFuture channelFuture;
    private static Boolean ifConnecting = false;
    private static Boolean ifConnected = false;
    private static Boolean noChance = false;

    /**
     * 失败重连机制，参考Netty入门实战掘金小册
     *
     * @param bootstrap
     * @param host
     * @param port
     * @param retry
     */
    private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
        channelFuture = bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接服务端成功");
                ifConnected=true;
            } else if (retry == 0) {
                System.out.println("重试次数已用完，放弃连接");
                noChance=true;
                ifConnected=false;
            } else {
                //第几次重连：
                int order = (MAX_RETRY - retry) + 1;
                //本次重连的间隔
                int delay = 1 << order;
                System.out.println(new Date()+"{} : 连接失败，第 "+order+" 重连....");
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
            }
        });
        channel = channelFuture.channel();
    }



    public static Boolean heartBeatTest(String ip,int port) throws InterruptedException {
        ifConnected=false;
        noChance = false;
        //1.创建NioEventLoopGroup的实例对象
        EventLoopGroup group = new NioEventLoopGroup();

        //2.创建bootstrap对象
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new StringEncoder());
                    }
                });
//        connect(bootstrap, "127.0.0.1", 8000, MAX_RETRY);
//        Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();

        while (true){
//            x=channelFuture.channel().isActive();
            if (ifConnected){

                channel.writeAndFlush(new Date()+"心跳检测");
                Thread.sleep(2000);
                ifConnecting=false;
                break;
            } else if (!ifConnected&!ifConnecting) {//尝试重连
                connect(bootstrap, ip, port, MAX_RETRY);
                ifConnecting=true;
                Thread.sleep(2000);
            } else if (noChance){
                ifConnecting=false;
                break;
            } else {
                System.out.println("do no thing");
            }

            Thread.sleep(2000);
        }

        return ifConnected;
    }


    /*public static void main(String[] args) throws InterruptedException {

        for (int i = 0 ;i<2;i++){
            if (!ifConnected){
                boolean b = heartBeatTest("127.0.0.1",8000);
                System.out.println(b);
            }

        }

    }*/




}
